﻿using DLL.Net.DB.Recorder.CRUD.Service;
using DLL.Net.MS.Models;
using DLL.NET.Login.Account.Entity.DTO;

using DLL.NET50.DB.MS.AdviceAndDrug.ORM.Service;
using DLL.NET50.DB.MS.PIVASAndDicDrug.ORM;

using DLL.NET50.DB.PIVAS.ORM.Service;

using DLL.NET70.Infrastructure.EventAggregator;
using DLL.NET70.Infrastructure.Prism.MVVM;
using DLL.NetStandard.FlushRobot.MS.Entity.Param;
using DLL.Standard.Infrastructure.Entity;
using Microsoft.Extensions.Configuration;
using MySqlX.XDevAPI.Common;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Windows.Controls;

namespace Module.AutoRun.ViewModels
{
    public class PUC_MS_ScanBarViewModel : CMVVMBase, IRegionMemberLifetime
    {
        public bool KeepAlive
        {
            get
            {
                return false;//这个的作用是，只要离开当前切面，就注销掉当前页面
                //return true;//这个的作用是，只要离开当前切面，就注销掉当前页面
            }
        }

        #region property

        private string _scanBar = "";

        public string ScanBar
        {
            get { return _scanBar; }
            set { SetProperty(ref _scanBar, value); }
        }

        private string _scanedBar = "";

        public string ScanedBar
        {
            get { return _scanedBar; }
            set { SetProperty(ref _scanedBar, value); }
        }

        private bool _barFocus = false;

        public bool BarFocus
        {
            get { return _barFocus; }
            set
            {
                SetProperty(ref _barFocus, value);
            }
        }

        private string _adviceState = "";

        public string AdviceState
        {
            get { return _adviceState; }
            set { SetProperty(ref _adviceState, value); }
        }

        //StateColor
        private string _StateColor = "Green";

        public string StateColor
        {
            get { return _StateColor; }
            set { SetProperty(ref _StateColor, value); }
        }

        //AllEnable
        private bool _AllEnable = false;//"False"

        public bool AllEnable
        {
            get { return _AllEnable; }
            set
            {
                SetProperty(ref _AllEnable, value);
            }
        }

        //AdviceCount
        private string _AdviceCount = "0";

        public string AdviceCount
        {
            get { return _AdviceCount; }
            set { SetProperty(ref _AdviceCount, value); }
        }

        //EnableSurplusMode
        private bool _EnableSurplusMode = true;//"False"

        public bool EnableSurplusMode
        {
            get { return _EnableSurplusMode; }
            set
            {
                SetProperty(ref _EnableSurplusMode, value);
            }
        }

        //儿科模式
        private string _modeName = "";

        public string ModeName
        {
            get { return _modeName; }
            set { SetProperty(ref _modeName, value); }
        }

        //SelectedBatch
        private int _SelectedBatchIndex = 0;

        public int SelectedBatchIndex
        {
            get { return _SelectedBatchIndex; }
            set { SetProperty(ref _SelectedBatchIndex, value); }
        }

        private string _SelectedBatch = "";

        public string SelectedBatch
        {
            get { return _SelectedBatch; }
            set { SetProperty(ref _SelectedBatch, value); }
        }

        private List<string> _Batches = new List<string>();

        public List<string> Batches
        {
            get { return _Batches; }
            set { SetProperty(ref _Batches, value); }
        }

        //是否允许重配
        public int _reFlushModeIndex = 0;

        public int reFlushModeIndex
        {
            get { return _reFlushModeIndex; }
            set { SetProperty(ref _reFlushModeIndex, value); }
        }

        //SurplusModeIndxe
        public int _SurplusModeIndxe = 0;

        public int SurplusModeIndxe
        {
            get { return _SurplusModeIndxe; }
            set { SetProperty(ref _SurplusModeIndxe, value); }
        }

        private string _TextBackGround = "Gray";

        public string TextBackGround
        {
            get { return _TextBackGround; }
            set { SetProperty(ref _TextBackGround, value); }
        }

        #endregion property

        #region local Variable

        private int _TPFlushMode = 0;

        private int _readyOK = 0;
        private int InjectorIsNew = 1;//注射器是新的
        private int ConnectMode = 1;
        private CMS_WorkConfigParam _workConfig = new CMS_WorkConfigParam();//加工配置参数
        private CMS_DeviceConfigParam _deviceConfig = new CMS_DeviceConfigParam();//设备硬件参数

        #endregion local Variable

        #region interface delegate command

        public DelegateCommand<object> KeyDownCommand
        {
            get { return new DelegateCommand<object>(KeyDown); }
        }

        public DelegateCommand<object> KeyUpCommand
        {
            get { return new DelegateCommand<object>(KeyUp); }
        }

        //EnterKeyCommand
        public DelegateCommand EnterKeyCommand
        {
            get { return new DelegateCommand(EnterKey); }
        }

        //LostFocusCommand
        public DelegateCommand LostFocusCommand
        {
            get { return new DelegateCommand(LostFocus); }
        }

        public DelegateCommand GetFocusCommand
        {
            get { return new DelegateCommand(GetFocus); }
        }

        //按键按下响应函数
        private void KeyDown(object sender)
        {
            TextBox text = sender as TextBox;
            if (text != null)
            {
                string str = text.Text;
            }
        }

        //按键弹起响应函数
        private void KeyUp(object sender)
        {
            TextBox text = sender as TextBox;
            if (text != null)
            {
                string str = text.Text;
            }
        }

        //响应回车键
        private void EnterKey()
        {
            _barProcess.SurplusMode = SurplusModeIndxe;
            _barProcess.TPFlushMode = _TPFlushMode;
            _barProcess.reFlushModeIndex = reFlushModeIndex;
            _barProcess.SelectedBatch = SelectedBatch;
            int ret = _barProcess.ProcessScanBar(ScanBar);
            if (ret == 0)
            {
                AdviceState = _barProcess.ErrorInfo;
                StateColor = "Red";
            }
            else
            {
                AdviceState = "正常";
                StateColor = "Green";
            }
            reFlushModeIndex = _barProcess.reFlushModeIndex;
            ScanedBar = ScanBar;
            ScanBar = "";
            //设置焦点
            BarFocus = true;
        }

        private void LostFocus()
        {
            //RosyBrown
            BarFocus = false;
            TextBackGround = "Gray";
        }

        private void GetFocus()
        {
            TextBackGround = "Green";
        }

        #endregion interface delegate command

        #region navigate

        private CNavigateTopParam _NavigateTopParam = new CNavigateTopParam();

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            //return PageViews / 3 != 1;
            var obj = navigationContext.Parameters["topParam"] as CNavigateTopParam;
            if (obj != null)
            {
                //if (obj.Length > 0)
                {
                    int v = Convert.ToInt32(obj.AllEnable);
                    if (1 == v)
                    {
                        AllEnable = true;
                    }
                    else
                    {
                        AllEnable = false;
                    }
                }
                _NavigateTopParam = obj;
                _TPFlushMode = _NavigateTopParam.TPFlushMode;
                _barProcess.TPFlushMode = _NavigateTopParam.TPFlushMode;
                _barProcess.ConnectMode = _NavigateTopParam.DeviceConnectkMode;
                _barProcess.CanUsedLabelStation = _NavigateTopParam.CanUsedStation;
                _barProcess.maxSolventCount = _NavigateTopParam.StationColNum;
                _barProcess.ResetValidHadScanedBar();
            }
            base.OnNavigatedTo(navigationContext);
        }

        #endregion navigate

        private IEventAggregator _eventAggregator;
        private IRegionManager _regionManager;
        private IAdviceExecuteService _pivasAdviceService;
        private IAdviceAndDicDrugsService _adviceAndDicDrugsService;
        private IDialogService _dialogService;
        private IPIVASAndDicDrug _sZPIVASAndDicDrug;
        private adi_accountDTO _logAccount;
        private IAdviceRecordService _RecorderService;
        private IMS_ScanBar _barProcess;

        public PUC_MS_ScanBarViewModel(IRegionManager regionManager,
            IEventAggregator eventAggregator,
            IContainerExtension container,
            IAdviceAndDicDrugsService adviceAndDicDrugsService,
            IPIVASAndDicDrug sZPIVASAndDicDrug,
            IDialogService dialogService,
            IAdviceRecordService RecorderService,

            IAdviceExecuteService pivasAdviceService,
            IMS_ScanBar scanBar
            ) : base(regionManager, eventAggregator)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _pivasAdviceService = pivasAdviceService;
            _adviceAndDicDrugsService = adviceAndDicDrugsService;
            _dialogService = dialogService;
            _sZPIVASAndDicDrug = sZPIVASAndDicDrug;
            _RecorderService = RecorderService;
            _pivasAdviceService = pivasAdviceService;
            _logAccount = container.Resolve<adi_accountDTO>();
            reFlushModecbSelectedChangedCommand = new DelegateCommand(ReflushModecbSelectedChanged);
            SurplusModecbSelectedChangedCommand = new DelegateCommand(SurplusModecbSelectedChanged);                                                                                   // SetSubscribe();
            BarFocus = false;
            _barProcess = scanBar;//new CMS_ScanBar(eventAggregator, pivasAdviceService, _logAccount);
        }

        private static IConfiguration Configuration { get; set; }

        public override void Loaded()
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            // 读取数组
            Batches = Configuration.GetSection("Batches").Get<List<string>>();

            if (AllEnable == true)
            {
                BarFocus = true;
                TextBackGround = "Green";
            }
            RegisterCommandMsgReceive();
            ReadParam();
            //string _url = "http://localhost:8085/WebServiceCharge.asmx";
            //charge = new CLocalUrl_ChargeInterface(_url);
        }

        public override void UnLoaded()
        {
            UnRegisterCommandMsgReceive();
            base.UnLoaded();
        }

        private void ReadParam()
        {
            CMS_WR_WorkConfigParam wrparam = new CMS_WR_WorkConfigParam();
            bool ret = wrparam.ReadParam();
            if (true == ret)
            {
                _workConfig = wrparam.Param;
            }
            CMS_WR_DeviceConfigParam wr_deviceConfig = new CMS_WR_DeviceConfigParam();
            wr_deviceConfig.ReadParam();
            _deviceConfig = wr_deviceConfig.Param;
        }

        public DelegateCommand reFlushModecbSelectedChangedCommand { get; private set; }

        private void ReflushModecbSelectedChanged()
        {
            if (reFlushModeIndex == 1)
            {
                //发送消息给配药界面，允许这个要重新配
                //SendMssageToPUC_MS_AutoFlush(CCommandStr.ReFlushMode, reFlushModeIndxe);
            }
            BarFocus = true;
            _barProcess.reFlushModeIndex = reFlushModeIndex;
        }

        public DelegateCommand SurplusModecbSelectedChangedCommand { get; private set; }

        private void SurplusModecbSelectedChanged()
        {
            //SendMssageToPUC_MS_AutoFlush(CCommandStr.SurplusMode, SurplusModeIndxe);
            BarFocus = true;
        }

        #region 接收消息

        public override void CommandMessageReceived(CCommandMessage message)
        {
            if (MSDM_CmdStr.ReplaceInjectorStart == message.CommandStr)
            {
                //换针开始
                _barProcess.InitializeCurrentUsedDrug();
                InjectorIsNew = 1;
                int value = int.Parse(message.value);
                if (value == 0)
                {
                    //没有达到使用寿命的换针
                    EnableSurplusMode = true;
                }
                else
                {
                }
                AllEnable = false;
                BarFocus = false;
            }
            else if (MSDM_CmdStr.ReplaceInjectorOver == message.CommandStr)
            {
                //换针结束
                AllEnable = true;
                _barProcess.InitializeCurrentUsedDrug();

                int value = int.Parse(message.value);
                if (value == 0)
                {
                    //没有达到使用寿命的换针
                    EnableSurplusMode = true;
                }
                else
                {
                }
                if (InjectorIsNew == 1)
                {
                    EnableSurplusMode = true;
                }
                InjectorIsNew = 1;
                BarFocus = true;
            }
            else if ((MSDM_CmdStr.PutDrugOver == message.CommandStr))
            {
                //AllEnable = false;
                BarFocus = true;
            }
            else if (MSDM_CmdStr.Clear == message.CommandStr)
            {
                //清空瓶贴
                ScanBar = "";
                AdviceState = "";
                ScanedBar = "";
                StateColor = "White";
                _barProcess.SendClearLablesMessage();
                _barProcess.InitializeAdvices();//初始化医嘱
                BarFocus = true;
            }
            else if ((MSDM_CmdStr.Focus == message.CommandStr))
            {
                if ("1" == message.value)
                {
                    BarFocus = true;
                }
                else if ("0" == message.value)
                {
                    BarFocus = false;
                }
            }
            else if ((MSDM_CmdStr.ConnectMode == message.CommandStr))
            {
                //本地模式，联机计费模式
                ConnectMode = int.Parse(message.value);
                _barProcess.ConnectMode = ConnectMode;
                BarFocus = true;
            }
            else if ((MSDM_CmdStr.TPFlushMode == message.CommandStr))
            {
                //统配，混配模式
                int mode = Convert.ToInt32(message.value);
                _TPFlushMode = mode;
                _barProcess.TPFlushMode = mode;
                //模式切换的时候，没有配药的情况下，清空瓶贴，清空配药记录
                if (InjectorIsNew == 1)
                {
                    _barProcess.SendClearLablesMessage();
                    _barProcess.InitializeAdvices();//初始化医嘱

                    _barProcess.InitializeCurrentUsedDrug();//初始化药品记录信息
                }
                //混配模式下，
                if (_TPFlushMode == 0)
                {
                    //混配模式
                    SurplusModeIndxe = 0;//设置成不结余模式
                    EnableSurplusMode = false; //屏蔽结余模式选择
                }
                else
                {
                    SurplusModeIndxe = 0;//设置成不结余模式
                    EnableSurplusMode = true; //屏蔽结余模式选择
                }
                BarFocus = true;
            }
            else if ((MSDM_CmdStr.Runing == message.CommandStr))
            {
                //设备开始配药
                InjectorIsNew = 0;//注射器变更为以使用
                EnableSurplusMode = false;
                BarFocus = false;
            }
            else if ((MSDM_CmdStr.RunOver == message.CommandStr))
            {
                EnableSurplusMode = false;
                BarFocus = true;
            }
            else if ((MSDM_CmdStr.ResetStart == message.CommandStr))
            {
                AllEnable = false;
                BarFocus = false;
            }
            else if ((MSDM_CmdStr.ResetOver == message.CommandStr))
            {
                //复位成功
                AllEnable = true;
                EnableSurplusMode = true;
                InjectorIsNew = 1;
                BarFocus = true;
            }
            base.CommandMessageReceived(message);
        }

        #endregion 接收消息
    }
}